/**
 * Created by Mark_ren on 2016/11/28.
 * 苟富贵,無相忘
 */
var moment = require("moment");
var co = require('co');
var request = require('request');
var querystring = require('querystring');
var seqModule = require('../../../routes/createModules');
var seq = new seqModule();
var util = require('../../../common/util');


var qdQrCodeController = {
    getQdQrCodePage: function (req, res) {
        co(function () {
            var params = {};
            var paramT = {};
            var include = []
            var qdwJ = { model: seq.qdWjModule, attributes: ['title'] };
            if (req.query.title != undefined) {
                qdwJ.where = { "title": { "$like": "%" + req.query.title + "%" } };
            }
            include.push(qdwJ);
            paramT.include = include;
            if (req.query.wjId != undefined && req.query.wjId != null && req.query.wjId != "") {
                params.wjId = parseInt(req.query.wjId);
            } else {
                params["$or"] = [{ "wjId": null }, { "wjId": "" }];
            }
            if (req.query.qrCode != undefined) {
                params.qrCode = { "$like": "%" + req.query.qrCode + "%" };
            }
            paramT.where = params;
            paramT.order = [["createTime", "DESC"]];
            var page = parseInt(req.query.page);
            if (req.query.page != undefined && req.query.rows != undefined) {
                paramT["offset"] = parseInt(req.query.page);
                paramT["limit"] = parseInt(req.query.rows);
            }
            seq.qdQrModule.findAndCountAll(paramT).then(function (result) {
                res.json({
                    'success': true, 'msg': '查询成功', 'page': page, 'total': result.count, 'result': result.rows
                });
            })

        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })
    },
    getQrCodeById: function (req, res) {
        co(function () {
            var paramT = {};
            paramT.where = req.params;
            seq.qdQrModule.findOne(paramT).then(function (result) {
                res.json({ 'success': true, 'msg': '查询成功', 'result': result });
            })

        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '查询失败' });
            console.log(e);
        })
    },
    addQdQrCode: function (req, res) {
        co(function () {
            if (req.method.toLowerCase() == 'post') {
                // parse a file upload
                var form = new formidable.IncomingForm();
                //files = [],
                //fields = [];
                form.uploadDir = "public/data/qrImage";
                form.type = true;

                form.on("progress", function (bytesReceived, bytesExpected) {
                    console.log("progress!" + bytesReceived + " B____" + (bytesExpected / 1024 / 1024).toFixed(2) + " MB");
                    // 百分比
                    var percent = Math.round(bytesReceived / bytesExpected * 100);
                    console.log("percent:" + percent + "%");
                    // 存入
                    //sessions.setSession(req,res,opts);
                });
                form.parse(req, function (err, fields, files) {
                    // res.render('index', { paths: [files.upload.name] });

                    if (files.qrImage != null && files.qrImage.name != "") {

                        var imgType = files.qrImage.name.split(".");
                        files.qrImage.name = "qrImage_" + moment().format("YYYYMMDDHHmmss") + "." + imgType[imgType.length - 1];
                        fs.renameSync(files.qrImage.path, form.uploadDir + "/" + files.qrImage.name);
                        fields["qrImage"] = files.qrImage.name;
                    }
                    fields.id = util.getUUID();
                    fields.createTime = util.getNowTime();
                    seq.qdQrModule.create(fields).then(function (qdMeet) {
                        res.redirect(util.getIP() + "qdQrCode/qrCodeList.html");
                    })

                });
            }
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '添加失败' });
            console.log(e);
        })
    },
    updateQdQrCode: function (req, res) {
        co(function () {
            var qrCode = req.body.qrCode;
            seq.qdQrModule.count({ where: { qrCode: qrCode, id: { $ne: req.params.id } } }).then(function (qrQrCount) {
                if (qrQrCount == 0) {
                    util.getAccessToken(function (accessToken) {
                        var url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
                        var jsonData = { "action_name": "QR_LIMIT_STR_SCENE", "action_info": { "scene": { "scene_str": qrCode } } };
                        request({
                            url: url,
                            method: "post",
                            json: true,
                            headers: {
                                "content-type": "application/json",
                            },
                            body: jsonData
                        },
                            function (error, response, data) {
                                if (!error && response.statusCode == 200) {
                                    var strData = JSON.stringify(data);
                                    var jsonData = JSON.parse(strData);
                                    var ticket = jsonData.ticket;
                                    var qrUrl = jsonData.url;
                                    var qrImage = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + encodeURIComponent(ticket);

                                    if (req.query.wjId != undefined) {
                                        req.body.wjId = wjId;
                                    }
                                    if (req.query.pushType != undefined) {
                                        req.body.pushType = parseInt(req.query.pushType);
                                    }
                                    req.body.qrImage = qrImage;
                                    req.body.qrUrl = qrUrl;
                                    seq.qdQrModule.update(req.body, { where: req.params }).then(function (data) {
                                        res.json({ 'success': true, 'msg': '修改成功' });
                                    })
                                } else {
                                    res.json({ 'success': false, 'msg': '请求失败' });
                                }


                            });
                    })

                } else {
                    res.json({ 'success': false, 'msg': '该二维码已存在' });
                }
            })



        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '修改失败' });
            console.log(e);
        })
    },
    deleteQdQrCode: function (req, res) {
        co(function () {
            var params = req.query.params;
            var arr = params.split(",");
            var paramT = [arr];
            seq.qdQrModule.destroy({ where: { id: paramT } }).then(function (qdMeet) {
                res.json({ 'success': true, 'msg': '删除成功' });
            })
        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })
    },
    createQrCode: function (req, res) {
        co(function () {
            var qrCode = req.query.qrCode;
            seq.qdQrModule.count({ where: { qrCode: qrCode } }).then(function (qrQrCount) {
                if (qrQrCount == 0) {
                    util.getAccessToken(function (accessToken) {
                        var url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
                        var jsonData = { "action_name": "QR_LIMIT_STR_SCENE", "action_info": { "scene": { "scene_str": qrCode } } };
                        request({
                            url: url,
                            method: "post",
                            json: true,
                            headers: {
                                "content-type": "application/json",
                            },
                            body: jsonData
                        },
                            function (error, response, data) {
                                if (!error && response.statusCode == 200) {
                                    var strData = JSON.stringify(data);
                                    var jsonData = JSON.parse(strData);
                                    var ticket = jsonData.ticket;
                                    var qrUrl = jsonData.url;
                                    var qrImage = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + encodeURIComponent(ticket);
                                    var params = {};
                                    if (req.query.wjId != undefined) {
                                        params.wjId = req.query.wjId;
                                    }
                                    if (req.query.pushType != undefined) {
                                        params.pushType = parseInt(req.query.pushType);
                                    }
                                    params.id = util.getUUID();
                                    params.qrCode = qrCode;
                                    params.qrImage = qrImage;
                                    params.qrUrl = qrUrl;
                                    seq.qdQrModule.create(params).then(function (data) {
                                        res.json({ 'success': true, 'msg': '二维码生成成功', 'result': data });
                                    })
                                } else {
                                    res.json({ 'success': false, 'msg': '请求失败' });
                                }


                            });
                    })
                } else {
                    res.json({ 'success': false, 'msg': '该二维码已存在' });
                }
            })

        }).catch(function (e) {
            res.json({ 'success': false, 'msg': '删除失败' });
            console.log(e);
        })

    }

}
module.exports = qdQrCodeController;